<template>
  <div class="box">
    <div class="search">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="输入部门名称/部门编号查询" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchDepartment">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="searchForm.status" @change="handleCheck" style="margin-left: 10px;">显示禁用部门</el-checkbox>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="openAddDialog" style="margin-left: auto;">
        新增
      </el-button>
      <el-button plain>导出</el-button>
      <el-button type="plain" @click="batchRemove" style="margin-left: 10px;">
        删除
      </el-button>
    </div>


    <el-dialog v-model="dialogFormVisible" :title="dialogType === 'add' ? '新增部门' : '编辑部门'" width="500" draggable
      overflow>
      <el-form :model="form">
        <el-form-item label="部门名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>

        <el-form-item label="部门分类" :label-width="formLabelWidth">
          <el-select v-model="form.category" placeholder="请选择部门分类">
            <el-option v-for="item in departmentCategory" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" :label-width="formLabelWidth">
          <el-select v-model="form.staffId" placeholder="请选择" style="flex: 1;" ref="selectRef" suffix-icon="More">
            <el-option v-for="item in staffs" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDepartment">
            确认
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogCategoryVisible" :title="dialogCategoryType === 'add' ? '新增分类' : '编辑分类'" width="500"
      draggable overflow>
      <el-form :model="categoryForm">
        <el-form-item label="分类名称" :label-width="formLabelWidth">
          <el-input v-model="categoryForm.name" autocomplete="off" />
        </el-form-item>

        <el-form-item label="上级分类" :label-width="formLabelWidth">
          <el-tree-select v-model="categoryForm.parentId" :data="treeSelectData" check-strictly filterable
            :render-after-expand="false" :props="{ value: 'id', label: 'name', children: 'children' }">
            <template #default="{ data }">
              {{ data.name }}
            </template>
          </el-tree-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDepartmentCategory">
            确认
          </el-button>
          <el-button @click="dialogCategoryVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="main">
      <!-- 左侧分类树 -->
      <el-card
        :style="{ width: isCollapse ? '280px' : '48px', display: 'flex', flexDirection: 'column', transition: 'width 0.3s ease' }">
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span v-if="isCollapse">部门分类</span>
            <el-button :icon="isCollapse ? 'DArrowLeft' : 'DArrowRight'" @click="toggleCollapse"
              style="border: none; padding: 0px;" />
          </div>
        </template>

        <div v-if="isCollapse" style="flex: 1; overflow: auto;">
          <el-tree :data="treeSelectData" node-key="id" default-expand-all highlight-current
            :props="{ label: 'name', children: 'children' }" ref="treeRef" @node-click="handleNodeClick"
            style="border: none;" v-loading="treeLoad">

            <template #default="{ data }">
              <div class="tree-node" @mouseenter="hoveredNodeId = data.id" @mouseleave="hoveredNodeId = null"
                style="width: 100%;">
                <span>{{ data.name }}</span>

                <span>
                  <!-- 普通节点：hover 时显示操作按钮 -->
                  <template v-if="hoveredNodeId === data.id">
                    <!-- 新增：仅允许在第1、2层（level < 3） -->
                    <el-button v-if="data.level < 3" class="tree_button" icon="CirclePlus" size="small"
                      @click.stop="openAddDialogCategory(data)" />

                    <!-- 编辑 & 删除：所有普通分类都支持 -->
                    <el-button v-if="data.id !== '0'" class="tree_button" icon="Edit" size="small"
                      @click.stop="updateDepartmentCategory(data.id)" />
                    <el-button v-if="data.id !== '0'" class="tree_button" icon="Delete" size="small"
                      @click.stop="deleteCategory(data)" />
                  </template>
                </span>
              </div>
            </template>
          </el-tree>
        </div>
      </el-card>

      <!-- 右侧表格区域 -->
      <el-card style="flex: 1; display: flex; flex-direction: column; overflow: hidden;">
        <!-- 表格容器：撑满剩余空间 -->
        <div style="flex: 1; min-height: 0; overflow: auto;">
          <el-table :data="tableData" border style="width: 100%;" @selection-change="handleSelection"
            v-loading="tableLoad">
            <el-table-column type="selection" fixed width="55" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="name" label="部门名称" width="120" />
            <el-table-column prop="code" label="部门编号" width="120" />
            <el-table-column prop="category" label="部门类别" width="120">
              <template #default="scope">
                {{departmentCategory.find(item => item.id === scope.row.category)?.name || '无'}}
              </template>
            </el-table-column>
            <el-table-column prop="staffId" label="负责人" width="80">
              <template #default="scope">
                {{staffs.find(item => item.id === scope.row.staffId)?.name || '无'}}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="100" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-switch :model-value="scope.row.status" :active-value="1" :inactive-value="0"
                  @change="() => handleStatusChange(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button type="primary" icon="Edit" @click="updateDepartment(scope.row.id)" size="small" />
                <el-button type="danger" icon="Delete" @click="singleRemove(scope.row.id)" size="small" />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <template #footer>
          <div class="demo-pagination-block" style="float: right;">
            <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
              :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
              :total="pageInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, computed } from 'vue'
import axios from 'axios'

const tableLoad = ref(false)

const treeLoad = ref(false)

// 添加用于跟踪悬停节点ID的响应式变量
const hoveredNodeId = ref(null)

// 左侧展开、关闭
const isCollapse = ref(true)

// 切换
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 对话框
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const dialogType = ref('add') // 'add' 或 'edit'

// 类别对话框
const dialogCategoryVisible = ref(false)
const dialogCategoryType = ref('add')

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: 1,
  category: null,
})

// 添加表单
const form = ref({
  name: '',
  code: '',
  category: '',
  staffId: '',
  remark: '',
})

// 类别表单 
const categoryForm = ref({
  name: '',
  parentId: '',
})

const pageInfo = reactive({
  total: 0,
  pageSize: 10,
  pageNum: 1,
})


// 表格数据（部门）
const tableData = ref([])

const getDepartments = async () => {
  tableLoad.value = true
  try {
    const res = await axios.get("/api/basic/enterprise/departmentByPage", {
      params: {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        ...searchForm
      }
    })

    if (res.data.code === 5200) {
      tableData.value = res.data.pageInfo.list
      pageInfo.total = res.data.pageInfo.total
      pageInfo.pageNum = res.data.pageInfo.pageNum
      tableLoad.value = false
    } else {
      ElMessage.error('获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('加载失败')
  }
}

// 部门分类
const departmentCategory = ref([])

const getDepartmentCategory = async () => {
  treeLoad.value = true
  try {
    const res = await axios.get("/api/basic/enterprise/allDepartmentCategory")

    if (res.data.code === 5200) {
      departmentCategory.value = res.data.departmentCategoryList
      treeLoad.value = false
    } else {
      ElMessage.error('获取部门分类列表失败')
    }
  } catch (error) {
    console.error('获取部门分类列表失败:', error)
    ElMessage.error('加载失败')
  }
}

// 构建树形数据
const treeData = computed(() => {
  const roots = []
  const map = {}

  departmentCategory.value.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  departmentCategory.value.forEach(item => {
    if (item.parentId === null || item.parentId == 0) {
      roots.push(map[item.id])
    } else {
      const parentObj = map[item.parentId]
      if (parentObj) {
        parentObj.children.push(map[item.id])
      }
    }
  })

  // 分配级别
  const assignLevel = (nodes, level) => {
    nodes.forEach(node => {
      node.level = level
      if (node.children && node.children.length > 0) {
        assignLevel(node.children, level + 1)
      }
    })
  }
  assignLevel(roots, 1)
  return roots
})

const treeSelectData = computed(() => {
  const enabledTreeData = treeData.value
  return [
    {
      id: '0',
      name: '全部',
      level: 0,
      children: enabledTreeData
    }
  ]
})

// 获取员工数据（或者根据对应部门类别下的员工）
const staffs = ref([])

const getStaffList = async () => {
  try {
    const res = await axios.get("/api/basic/enterprise/allStaff")

    if (res.data.code === 5200) {
      staffs.value = res.data.staffList
    } else {
      ElMessage.error('获取员工列表失败')
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('加载失败')
  }
}


const handleCheck = (checked) => {
  searchForm.status = checked ? null : 1
  getDepartments()
}

const searchDepartment = () => {
  pageInfo.pageNum = 1
  getDepartments()
}

//状态切换
const handleStatusChange = async (row) => {
  try {
    const res = await axios.post('/api/basic/enterprise/updateDepartmentStatus', null, {
      params: { id: row.id }
    })
    if (res.data.code !== 5200) {
      ElMessage.error('状态更新失败')
    } else {
      ElMessage.success('状态更新成功')
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试')
  } finally {
    await getDepartments();
  }
}

// 左侧节点点击搜索
const handleNodeClick = (nodeData) => {
  searchForm.category = nodeData.id == 0 ? null : nodeData.id
  pageInfo.pageNum = 1
  getDepartments()
}

const openAddDialog = () => {
  form.value = { name: '', code: '', category: '', staffId: '', remark: '' }
  dialogFormVisible.value = true
}

const updateDepartment = async (id) => {
  dialogType.value = 'edit'
  const res = await axios.get('/api/basic/enterprise/departmentById', { params: { id } })

  if (res.data.code === 5200) {
    form.value = res.data.department
    dialogFormVisible.value = true
  } else {
    ElMessage.error('获取数据失败')
  }
}

const submitDepartment = async () => {

  // 校验部门名称
  if (!form.value.name?.trim()) {
    ElMessage.error('请输入部门名称')
    return
  }

  // 校验部门分类
  if (!form.value.category) {
    ElMessage.error('请选择部门分类')
    return
  }

  try {

    const url = dialogType.value === 'add' ? '/api/basic/enterprise/addDepartment' : '/api/basic/enterprise/updateDepartment'

    const res = await axios.post(url, form.value)

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      dialogFormVisible.value = false
      await getDepartments()
    } else {
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  }
}

// ---- 类别 ---
const openAddDialogCategory = (data) => {
  categoryForm.value = { name: '', parentId: data.id }
  dialogCategoryVisible.value = true
}

const updateDepartmentCategory = async (id) => {

  if (id === '0' || id === 0) {
    return
  }


  dialogCategoryType.value = 'edit'
  const res = await axios.get('/api/basic/enterprise/departmentCategoryById', { params: { id } })

  if (res.data.code === 5200) {
    categoryForm.value = res.data.departmentCategory

    dialogCategoryVisible.value = true
  } else {
    ElMessage.error('获取数据失败')
  }
}

const submitDepartmentCategory = async () => {
  if (categoryForm.value.name === '') {
    ElMessage.error('请输入分类名称')
    return
  }
  if (categoryForm.value.parentId === '') {
    ElMessage.error('请选择上级分类')
    return
  }

  if(categoryForm.value.id === categoryForm.value.parentId){
    ElMessage.error('上级分类不能是当前分类')
    return;
  }

  try {

    const url = dialogCategoryType.value === 'add' ? '/api/basic/enterprise/addDepartmentCategory' : '/api/basic/enterprise/updateDepartmentCategory'

    const res = await axios.post(url, categoryForm.value)

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      dialogCategoryVisible.value = false
      await getDepartmentCategory()
    } else {
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('请求失败')
  }
}

const deleteCategory = async (data) => {

  if (data.id === '0' || data.id === 0) {
    return
  }

  await ElMessageBox.confirm('确定删除该分类吗？此操作不可恢复')

  try {

    if (data.children && data.children.length > 0) {
      ElMessage.warning('该分类下存在子分类，无法删除，请先删除子分类')
      return
    }

    const res = await axios.post('/api/basic/enterprise/deleteDepartmentCategory', null, { params: { id: data.id } })

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      getDepartmentCategory()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch {
    ElMessage.error('删除操作出现错误')
  }
}

const handleSizeChange = (val) => {
  pageInfo.pageSize = val
  pageInfo.pageNum = 1
}
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val
}

// 选中的对象
const selectedArray = ref([])
const selectedIds = computed(() => selectedArray.value.map(item => item.id))

const handleSelection = (selection) => {
  selectedArray.value = selection
}

// 单个删除
const singleRemove = async (id) => {
  deleteDepartment([id])
}

// 批量删除
const batchRemove = async () => {
  if (selectedArray.value.length === 0) {
    ElMessage.warning("请先选择要删除的供应商")
    return;
  }
  deleteDepartment(selectedIds.value)
}
// 删除供应商信息
const deleteDepartment = async (ids) => {
  try {

    await ElMessageBox.confirm('确定删除已经选中的供应商吗？此操作不可恢复')

    const res = await axios.post('/api/basic/enterprise/deleteDepartment', ids)

    if (res.data.code === 5200) {
      ElMessage.success(res.data.msg)
      getDepartments()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch {
    ElMessage.error('删除操作出现错误')
  }
}


onMounted(() => {
  getDepartments()
  getDepartmentCategory()
  getStaffList()
})
</script>

<style scoped>
.box {
  display: flex;
  flex-direction: column;
  padding: 16px;
  box-sizing: border-box;
}

.search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.main {
  display: flex;
  gap: 16px;
  flex: 1;
}

.search .el-form {
  flex: 1;
}

/* 搜索框样式 */
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

/* 折叠时卡片头部居中 */
.el-card__header {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 调整树节点的字体大小和行高（即上下间距） */
:deep(.el-tree-node__content) {
  height: 36px;
  line-height: 36px;
  font-size: 15px;
}

.tree_button {
  border: 0;
  padding: 8px 5px;
}

/* 让自定义节点内容占满整行 */
:deep(.el-tree-node__content) {
  width: 100%;
}
</style>